/**
 * COPYRIGHT HangZhou Trustway Technology Company Limited
 * All right reserved.
 */
package com.robam.cloud.authcenter.helper.impl;

import com.alibaba.fastjson.JSONObject;
import com.robam.cloud.authcenter.helper.ThirdAuthGateway;
import com.robam.cloud.common.bean.authcenter.dto.FaceParam;
import com.robam.cloud.common.bean.authcenter.entity.AuthPlatform;
import com.robam.cloud.common.bean.authcenter.entity.FaceRes;
import com.robam.cloud.common.bean.common.Constant;
import com.robam.cloud.common.bean.restful.entity.ServiceException;
import com.robam.cloud.common.bean.usercenter.entity.LoginAccount;
import com.robam.cloud.common.bean.usercenter.entity.User;
import com.robam.cloud.common.bean.usercenter.entity.UserSession;
import com.robam.cloud.common.util.RequestUtil;
import com.robam.cloud.common.util.UuidUtil;
import com.robam.cloud.common.util.alipay.AlipayUser;
import com.robam.cloud.common.util.alipay.AlipayUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @Description
 * @Author 薛铁琪
 * @CreateTime 2020-07-20 16:03
 * @Version 1.0
 */
@Component
@Slf4j
public class AlipayAuthGateway extends ThirdAuthGateway {


    @Autowired
    AlipayUtil alipayUtil;
    @Autowired
    RedisTemplate redisTemplate;


    @Override
    public UserSession getUserSession(AuthPlatform authPlatform, JSONObject request, HttpServletRequest httpServletRequest) {
        AlipayUser alipayUser = alipayUtil.getAlipayUser(request.getString("code"), authPlatform.getAppId(), authPlatform.getPrivatekey(), authPlatform.getPublickey());
        log.debug("alipayuser={}", alipayUser.toString());
        if (alipayUser != null) {
            String isCertificatied = alipayUser.getIsCertificatied();
            if (isCertificatied.equals("T")) {
                LoginAccount loginAccount = LoginAccount.builder()
                        .platformId(authPlatform.getId())
                        .accountOpenid(alipayUser.getUserId())
                        .nickname(alipayUser.getNickName())
                        .sex(alipayUser.getAvatar())
                        .zcip(RequestUtil.getIpAddress(httpServletRequest))
                        .zcsj(new Date())
                        .rzsj(new Date())
                        .build();
                if (AlipayUser.MALE.equals(alipayUser.getAvatar())) {
                    loginAccount.setSex(LoginAccount.MALE);
                } else if (AlipayUser.FEMALE.equals(alipayUser.getAvatar())) {
                    loginAccount.setSex(LoginAccount.FEMALE);
                }
                User user = User.builder()
                        .sfzmhm(alipayUser.getCertNo())
                        .sfzmmc("A")
                        .sjhm(alipayUser.getMobile())
                        .xm(alipayUser.getUserName())
                        .zcip(RequestUtil.getIpAddress(httpServletRequest))
                        .zcsj(new Date())
                        .build();
                loginAccount.setAccountOpenid(alipayUser.getUserId());
                loginAccount.setNickname(alipayUser.getNickName());
                return UserSession.builder().user(user).loginAccount(loginAccount).build();
            } else {
                throw new ServiceException("支付宝三方登陆异常请稍后重试");
            }
        } else {
            throw new ServiceException("支付宝三方登陆异常请稍后重试");
        }
    }

    @Override
    public FaceParam getFaceParam(AuthPlatform authPlatform, String certNo, String certType, String certName, String sfbr, String expireTime, String token) {
        String certifyId = "";
        if (StringUtils.isNotEmpty(certNo) && StringUtils.isNotEmpty(certName)) {
            certifyId = alipayUtil.getCertifyId(certName, certNo, sfbr, authPlatform.getAppId(), authPlatform.getPrivatekey(), authPlatform.getPublickey());
        }
        if (StringUtils.isEmpty(certifyId)) {
            log.error("初始化身份认证单据号失败,certifyId={}", certifyId);
            throw new ServiceException("支付宝扫脸暂不可用，请稍后再试");
        }
        String certifyUrl = alipayUtil.getCertifyUrl(certifyId, authPlatform.getAppId(), authPlatform.getPrivatekey(), authPlatform.getPublickey());
        if (StringUtils.isEmpty(certifyUrl)) {
            log.error("生成认证服务请求地址失败,certifyUrl={}", certifyUrl);
            throw new ServiceException("支付宝扫脸暂不可用，请稍后再试");
        }
        String bizNo = UuidUtil.createUuid(Constant.FACEBIZNO);
        FaceParam faceParam = FaceParam.builder()
                .faceBizNo(bizNo)
                .faceSfzmhm(certNo)
                .faceSfzmmc(certType)
                .faceXm(certName)
                .aliFaceCertifyId(certifyId)
                .aliFaceUrl(certifyUrl)
                .build();
        redisTemplate.opsForValue().set(Constant.FACEBIZNO + ":" + token, bizNo, Long.parseLong(expireTime), TimeUnit.MINUTES);
        redisTemplate.opsForValue().set(Constant.FACECERTIFYID + ":" + token, certifyId, Long.parseLong(expireTime), TimeUnit.MINUTES);
        redisTemplate.opsForValue().set(Constant.FACEBIZNO + ":" + bizNo, false, Long.parseLong(expireTime), TimeUnit.MINUTES);
        return faceParam;
    }

    @Override
    public void verifyFaceResult(AuthPlatform authPlatform, FaceRes faceRes, String token) {
        String bizNo = String.valueOf(redisTemplate.opsForValue().get(Constant.FACEBIZNO + ":" + token));
        String certifyId = String.valueOf(redisTemplate.opsForValue().get(Constant.FACECERTIFYID + ":" + token));

        if (faceRes != null) {
            String resultStatus = faceRes.getResultStatus();
            if (!"9000".equals(resultStatus)) {
                log.error("getAliResultByFace error={}", faceRes);
                throw new ServiceException("扫脸异常，请重试");
            }
        } else {
            throw new ServiceException("扫脸参数异常");
        }

        String materialInfo = alipayUtil.certifyQuery(certifyId, authPlatform.getAppId(), authPlatform.getPrivatekey(), authPlatform.getPublickey());
        if (StringUtils.isNotEmpty(materialInfo) && !("{}".equals(materialInfo))) {
            //如果多人扫脸，直到本人扫脸通过后标记true，需要前端将本人扫脸放在最后一次
            redisTemplate.opsForValue().set(Constant.FACEBIZNO + ":" + bizNo, true);
            try {

                //todo 异步调用上传阿里云
            } catch (Exception e) {
                log.error("getResultByFace　OSS照片上传异常", e);
            }
        }
        throw new ServiceException("扫脸结果验证失败");
    }


    public String getTimeBizNo() {
        String bizNo = "";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date();
        bizNo = simpleDateFormat.format(date);
        return bizNo;
    }

    @Override
    public String getMediaUrl(AuthPlatform authPlatform, String serverId) {
        return null;
    }
}
